package com.ilaisa.laishang

import android.text.TextUtils
import com.cherry.androidcode.util.getALiParams

/**
 * @author DongMS
 * @since 2020/4/10
 */
class ALiAuthResult(authResult: Map<String, String>?) {

    var resultStatus: String? = null
    var result: String? = null
    var memo: String? = null

    var userId: String? = null
    var authCode: String? = null
    var alipayOpenId: String? = null

    var authSuccess = false

    init {
        authResult?.let {
            for ((k, v) in authResult) {
                when (k) {
                    "resultStatus" -> resultStatus = v
                    "result" -> result = v
                    "memo" -> memo = v
                }
            }
        }

        var isSuccess = false
        var resultCode: String? = null
        if (!TextUtils.isEmpty(result)) {
            val split = result!!.split("&")
            for (value in split) {
                when {
                    value.startsWith("alipay_open_id") -> alipayOpenId = value.getALiParams("alipay_open_id=")
                    value.startsWith("auth_code") -> authCode = value.getALiParams("auth_code=")
                    value.startsWith("result_code") -> resultCode = value.getALiParams("result_code=")
                    value.startsWith("user_id") -> userId = value.getALiParams("user_id=")
                    value.startsWith("success") -> isSuccess = value.getALiParams("success=")?.toBoolean()
                            ?: false
                }
            }
        }
        authSuccess = "9000" == resultStatus && isSuccess && resultCode == "200"
    }

    override fun toString(): String {
        return "ALiAuthResult(resultStatus=$resultStatus, result=$result, memo=$memo, userId=$userId, authCode=$authCode, alipayOpenId=$alipayOpenId, authSuccess=$authSuccess)"
    }

}